package com.mdoya.controller;

import com.mdoya.response.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author mdoya
 * @version 1.0
 * @description: 公共Controller控制层
 */
@Slf4j
@RequestMapping("/common")
@RestController
public class BaseComtroller {
    /**
     *  配置yml指定路径
     */
    @Value("${reggie.path}")
    private String url;

    /**
     *  上传图片
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public ResultResponse upload(MultipartFile file, HttpServletRequest request){
        try {
            String oldFileName = file.getOriginalFilename();
            String fileSuffix = oldFileName.substring(oldFileName.lastIndexOf("."));
            // 自定义图片名称
            String fileName = UUID.randomUUID().toString().replace("-","") + fileSuffix;

            /*// tomcat-docbase.80.3341791546713456843
            // tomcat-docbase.80.7241630029225287898
            // tomcat-docbase.80.5076476487321345972
            // 每次启动Tomcat都是一个新的容器对象，所以啊 图片路径指定路径
            System.err.println("getContextPath：" + request.getServletContext().getContextPath());
            System.err.println("getResource：" + request.getServletContext().getResource("/"));
            System.err.println("getResource：" + request.getServletContext().getRealPath("/"));
            // 图片存在Tomcat项目根路径
            String projectUrl = request.getServletContext().getRealPath("/") + "image/" + fileName;
            log.info("image路径: {}",projectUrl);*/
            // 判断路径文件夹是否存在  不存在则创建文件夹
            File folder = new File(url);
            if (!folder.exists()){
                folder.mkdirs();
            }

            File pathFileName = new File(url, fileName);
            // 图片流转移到指定  路径和图片名称
            file.transferTo(pathFileName);
            return ResultResponse.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultResponse.error("上传失败");
        }
    }

    /**
     *      下载图片/回显图片显示
     * @param name 图片名称
     * @param response 写回前端
     * @return 可以不用返回值，图片写出去该请求已经结束了
     */
    @GetMapping("/download")
    public ResultResponse download(String name, HttpServletResponse response){
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(new File(url, name));
            outputStream = response.getOutputStream();
            // 1. IOUtils工具类拷贝图片流
//            IOUtils.copy(fileInputStream,outputStream);
            // 2. 自己拷贝图片流
            int len;
            byte[] bubyte = new byte[1024];

            while ((len = fileInputStream.read(bubyte)) != -1){
                outputStream.write(bubyte,0,len);
                outputStream.flush(); // 刷新缓冲流 避免有些数据没有写出
            }

            return ResultResponse.success("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultResponse.error("下载失败");
    }
}
